import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus,
  Inject,
} from '@nestjs/common';
import { Request, Response } from 'express';
import { Logger } from 'winston';

@Catch()
export class GlobalExceptionFilter implements ExceptionFilter {
  constructor(@Inject('winston') private readonly logger: Logger) {}
  catch(exception: unknown, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();
    const { method, url, ip, headers } = request;

    let status = HttpStatus.INTERNAL_SERVER_ERROR;
    let message = 'Internal server error';
    if (exception instanceof HttpException) {
      const res = exception.getResponse();
      const response: { message?: string } = typeof res === 'string' ? {} : res;
      status = exception.getStatus();
      message = response?.message ?? exception.message;
    } else if (exception instanceof Error) {
      message = exception.message;
    }

    this.logger.error('Error', {
      method,
      url,
      ip,
      userAgent: headers['user-agent'],
      time: `${Date.now()}`,
      error: message,
    });

    response.status(status).json({
      code: status,
      timestamp: new Date().toISOString(),
      path: request.url,
      message: message,
    });
  }
}
